import os
import json
import re
import sys
import uuid
import uvicorn
from pathlib import Path
from typing import Dict, Optional, Any, List
from fastmcp import Context, FastMCP
from datetime import datetime

# 创建MCP服务器实例
mcp = FastMCP("html-share-mcp-server")

domain = "http://green.mcp.clouddragon.huawei.com"
mcp_endpoint = "/mcp/html-share-mcp-server/http/"
local_base_dir = ""

def read_page_list(json_filepath: str) -> List[Dict[str, Any]]:
    if os.path.exists(json_filepath):
        with open(json_filepath, 'r', encoding='utf-8') as f:
            page_list = json.load(f)
    else:
        page_list = {}
    return page_list


def write_page_list(json_filepath: str, page_list: List[Dict[str, Any]]):
    os.makedirs(os.path.dirname(json_filepath), exist_ok=True)
    with open(json_filepath, 'w', encoding='utf-8') as f:
        json.dump(page_list, f, ensure_ascii=False, indent=2)


def write_html_file(html_filepath: str, html: str):
    os.makedirs(os.path.dirname(html_filepath), exist_ok=True)
    with open(html_filepath, 'w', encoding='utf-8') as f:
        f.write(html)


def get_groups_by_url(ctx: Context):
    """
    根据URL获取页面组
    """
    url = ctx.get_http_request().url
    path = url.path.replace(mcp_endpoint, "").strip().strip("/").strip().lower()
    path = re.sub(r"\s+|\.", "_", path)
    path = re.sub(r"/+", "/", path)
    if not path or path == "":
        now = datetime.now()
        path = f"daily/{now.year}/{now.month:02d}/{now.day:02d}"
    return path.split("/")


def is_valid_html(html: str) -> bool:
    """
    判断HTML内容是否有效
    """
    return html.strip().startswith("<html") and html.strip().endswith("</html>")


@mcp.tool()
def upload_html_page(
    html: str,
    title: str,
    description: str,
    id: Optional[str] = None,
    ctx: Context = None
):
    """
    上传一个静态HTML页面，返回一个可分享的URL地址
    
    Args:
        description: 页面描述
        html: HTML内容，确保内容符合标准的html格式，如<html>...</html>
        title: 页面标题
        id: 可选的id，如果传上一次请求返回的id，则覆盖上一次的html路径，否则自动生成一个id作为路径
    
    Returns:
        html的分享URL和id值
    """
    try:
        if not is_valid_html(html):
            return {
                "status": "error",
                "message": "HTML内容无效"
            }
        
        groups = get_groups_by_url(ctx)
        if not id:
            id = str(uuid.uuid4()).replace('-', '')
        
        html_filename = f"{id}-{title}.html" if title else f"{id}.html"
        html_filepath = os.path.join(local_base_dir, "media", "pages", *groups, f"{id[:3]}", f"{id[3:6]}", html_filename)
        write_html_file(html_filepath, html)
        
        url = f"{domain}/media/pages/{'/'.join(groups)}/{id[:3]}/{id[3:6]}/{html_filename}"

        json_filepath = os.path.join(local_base_dir, "media", "pages", *groups, "list.json")
        exist_pages = read_page_list(json_filepath)
        if id not in exist_pages:
            exist_pages[id] = {
                "id": id,
                "title": title,
                "url": url,
                "description": description,
                "created_at": datetime.now().isoformat()
            }
        write_page_list(json_filepath, exist_pages)            
        
        return {
            "status": "success",
            "url": url,
            "id": id
        }        
    except Exception as e:
        error_msg = f"保存HTML页面时出错: {str(e)}"
        print(error_msg)
        return {
            "status": "error",
            "message": error_msg,
        }


if __name__ == "__main__":
    http_app = mcp.http_app(path=mcp_endpoint)
    uvicorn.run(http_app, host="127.0.0.1", port=9001)